package cn.yangliu.security.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 杨柳
 * @date 2019-03-23
 */
@Component
public class CodeValidateFilter extends OncePerRequestFilter {

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Value("${loginUrl:/login}")
    private String loginUrl;

    private static final String LOGIN_METHOD = "post";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

       String url = request.getRequestURI();

       String method = request.getMethod();
       if (loginUrl.equals(url)&& LOGIN_METHOD.equalsIgnoreCase(method)){

            //校验逻辑
           String code = request.getParameter("code");

           try{
               if (!"1234".equalsIgnoreCase(code)){
                   throw new CodeAuthenticationException("验证码错误");
               }
           }catch (CodeAuthenticationException e){
               authenticationFailureHandler.onAuthenticationFailure(request,response,e);
               return;
           }
       }
       filterChain.doFilter(request,response);

    }

    static class CodeAuthenticationException extends AuthenticationException {

        public CodeAuthenticationException(String msg) {
            super(msg);
        }
    }
}
